package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;

/**
 * @author Du leilei
 * @version 1.0
 * @Description
 * @createTime 2023年09月03日 18:51:00
 */
@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {
    @Autowired
    private ApUserMapper apUserMapper;
    /**
     * app用户登录
     *
     * @param loginDto
     * @return
     */
    @Override
    public ResponseResult login(LoginDto loginDto) {

        //1.游客登录
        if (StringUtils.isBlank(loginDto.getPhone()) && StringUtils.isBlank(loginDto.getPassword())) {
            String token = AppJwtUtil.getToken(0L);
            HashMap<String, Object> resultMap = new HashMap<>();
            resultMap.put("token", token);
            return ResponseResult.okResult(resultMap);
        } else if (!(StringUtils.isBlank(loginDto.getPhone())) && !(StringUtils.isBlank(loginDto.getPassword()))) {
            //正常登录
            //1.根据用户名查询用户
            ApUser apUser = apUserMapper.selectOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, loginDto.getPhone()));
            //2.判断用户名是否存在 不存在 返回用户信息不存在
            if (apUser == null){
                return ResponseResult.errorResult(AppHttpCodeEnum.USER_NOT_EXIST);
            }
            //3.拿用户输入的密码拼接salt
            String inputPwd = DigestUtils.md5DigestAsHex((loginDto.getPassword() + apUser.getSalt()).getBytes());
            //4.比对密码
            //4.1不一致返回密码错误
            if (!(inputPwd.equals(apUser.getPassword()))){
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
            //5.登录成功，生成docker
            String token = AppJwtUtil.getToken(Long.valueOf(apUser.getId()));
            //6.登陆成功，将用户信息返回给前端
            HashMap<String, Object> userMap = new HashMap<>();
            userMap.put("id",apUser.getId());
            userMap.put("name",apUser.getName());
            userMap.put("phone",apUser.getPhone());

            //7.封装大map 将token和用户信息封装
            HashMap<String, Object> resultMap = new HashMap<>();
            resultMap.put("user",userMap);
            resultMap.put("token",token);
            return ResponseResult.okResult(resultMap);
        }else{
          return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

    }
}
